package xcmg.device.web.purchase;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.SendMethodDictionaryDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.purchase.PurchaseGroupDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.StringUtil;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.infra.enums.PurchaseStatus;
import xcmg.device.infra.interceptor.externalApiCheck.handle.ApiCheckStrategy;
import xcmg.device.service.basic.DataDictionaryService;
import xcmg.device.service.basic.SendMethodDictionaryService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.purchase.PurchaseRequestService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.DataDictionaryVO;
import xcmg.device.service.vo.purchase.PurchaseMaterialsShowVO;
import xcmg.device.service.vo.purchase.PurchaseRequestDetailVO;
import xcmg.device.service.vo.purchase.PurchaseRequestExternalVO;
import xcmg.device.service.vo.purchase.PurchaseRequestReportParamVO;
import xcmg.device.service.vo.purchase.PurchaseRequestVO;
import xcmg.device.service.vo.purchase.TimelinessReportParamVO;
import xcmg.device.service.warehouse.CommonService;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.RedisConstant;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by sqq on 2018/1/3.
 */
@Slf4j
@RestController
@RequestMapping("/purchaseRequest")
public class PurchaseRequestController extends BasicController {

    @Autowired
    private PurchaseRequestService purchaseRequestService;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;
    @Autowired
    private SendMethodDictionaryService sendMethodDictionaryService;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    //非直投只查询自己的零件信息的过滤配置
    private static final String SELF_MATERIAL_FILTER = "SELF_MATERIAL_FILTER";

    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult save(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {

        //参数预处理
        String userId = getUserId();
        String orgId = getOrgId();
        paramPreHandle(purchaseRequestVO, orgId);
        checkParam(purchaseRequestVO, orgId);
        purchaseRequestVO.setUpdateId(userId);
        purchaseRequestVO.setBillStatus(PurchaseStatus.Saved.toString());
        try {
            ErrorCode code;
            if (purchaseRequestVO.getBillId() == null || purchaseRequestVO.getBillId() == "") {
                if (purchaseRequestVO.getSeller()) {
                    purchaseRequestVO.setSupplierOrgId(orgId);
                } else {
                    purchaseRequestVO.setPurchaseOrgId(orgId);
                }
                purchaseRequestVO.setCreateId(userId);
                purchaseRequestVO.setCreateOrgId(orgId);
                //分布式锁处理
                String purchaseReuestCacheKey = RedisConstant.purchaseReuestCacheKey(purchaseRequestVO);
                RLock lock = redissonClient.getLock(purchaseReuestCacheKey);
                boolean isLock;
                try {
                    isLock = lock.tryLock(0, 60 * 30, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    log.error("提交采购申请零件获取分布式锁异常：{}", e);
                    return ActionResultUtil.errorActionResult(ErrorCode.Failure);
                }
                if (!isLock) {
                    log.warn("相同采购申请的数据在redis中已存在,无法获取锁，本次不执行");
                    return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(), "操作太快了,请检查是否已经提交");
                }
                try {
                    code = purchaseRequestService.insert(purchaseRequestVO, getOrgId(), "save", null);
                } finally {
                    lock.unlock();
                }
            } else {
                code = purchaseRequestService.update(purchaseRequestVO, getOrgId(), "save");
            }
            return actionResult(code);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    private void paramPreHandle(PurchaseRequestVO purchaseRequestVO, String orgId) {
        if (purchaseRequestVO == null) {
            return;
        }
        String shippingMethodId = purchaseRequestVO.getShippingMethodId();
        String shippingMethod = purchaseRequestVO.getShippingMethod();
        //一级发运方式 如果前端传了key没有传value的话后端不全
        if (StringUtils.isEmpty(shippingMethod) && !StringUtils.isEmpty(shippingMethodId)) {
            List<SendMethodDictionaryDO> sendMethods = sendMethodDictionaryService.item(orgId, "0", shippingMethodId);
            if (!CollectionUtils.isEmpty(sendMethods)) {
                shippingMethod = sendMethods.get(0).getName();
                purchaseRequestVO.setShippingMethod(shippingMethod);
            }
        }
        //如果前端传了一级发运方式&&传了2及发运方式，没有传2级发运方式的名称，则后端自动补全
        String sendTypeChildId = purchaseRequestVO.getSendTypeChildId();
        String sendTypeChildName = purchaseRequestVO.getSendTypeChildName();
        if (StringUtils.isEmpty(sendTypeChildName) && !StringUtils.isEmpty(shippingMethodId) && !StringUtils.isEmpty(sendTypeChildId)) {
            List<SendMethodDictionaryDO> sendMethods = sendMethodDictionaryService.item(orgId, shippingMethodId, sendTypeChildId);
            if (!CollectionUtils.isEmpty(sendMethods)) {
                sendTypeChildName = sendMethods.get(0).getName();
                purchaseRequestVO.setSendTypeChildName(sendTypeChildName);
            }
        }

    }

    @RequestMapping(value = "/adjust", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation("采购订单调整")
    public ActionResult adjust(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        if (null == purchaseRequestVO || null == purchaseRequestVO.getMaterialsList()
                || purchaseRequestVO.getMaterialsList().isEmpty()) {
            return actionResult(ErrorCode.IllegalArument);
        }

        String orgId = getOrgId();
        checkParam(purchaseRequestVO, orgId);

        purchaseRequestVO.setUpdateId(getUserId());
        purchaseRequestVO.setUpdateName(getUserName());
        try {
            return actionResult(purchaseRequestService.adjust(purchaseRequestVO, getOrgId()));
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/saveByPlan", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult saveByPlan(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        purchaseRequestVO.setUpdateId(getUserId());
        try {
            purchaseRequestVO.setCreateId(getUserId());
            purchaseRequestVO.setCreateOrgId(getOrgId());
            ErrorCode code = purchaseRequestService.insertByBuyPlan(purchaseRequestVO, getOrgId());
            return actionResult(code);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addPurchaseOrder", method = RequestMethod.POST)
    public ActionResult addPurchaseOrder(@RequestBody PurchaseRequestExternalVO model) throws Exception {
        LogHelper.monitor("addPurchaseOrder接口入参：" + model.toString());
        String billNo = "";
        try {
            billNo = purchaseRequestService.insert4External(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return actionValueResult(billNo);
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addPurchaseOrderBySec", method = RequestMethod.POST)
    @ExternalApiRequest(ApiCheckStrategy.ApiCheckOptionEnum.OPTION_SECRET)
    public ActionResult addPurchaseOrderBySec(@RequestBody PurchaseRequestExternalVO model) throws Exception {
        LogHelper.monitor("addPurchaseOrder接口入参：" + model.toString());
        String billNo = "";
        try {
            billNo = purchaseRequestService.insert4External(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return actionValueResult(billNo);
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addPurchase4GssAgent", method = RequestMethod.POST)
    @ExternalApiRequest(ApiCheckStrategy.ApiCheckOptionEnum.OPTION_SECRET)
    public ActionResult addPurchase4GssAgent(@RequestBody PurchaseRequestExternalVO model) throws Exception {
        LogHelper.monitor("addPurchase4GssAgent接口入参：" + model.toString());
        String billNo = "";
        try {
            billNo = purchaseRequestService.saveFromGSSAgent(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return actionValueResult(billNo);
    }


    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult submit(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        String orgId = getOrgId();
        checkParam(purchaseRequestVO, orgId);
        purchaseRequestVO.setUpdateId(getUserId());
        purchaseRequestVO.setBillStatus(PurchaseStatus.WaitAudit.toString());
        purchaseRequestVO.setSubmitDate(new Date());
        try {
            ErrorCode code;
            if (StringUtil.isEmpty(purchaseRequestVO.getBillId())) {
                if (purchaseRequestVO.getSeller()) {
                    purchaseRequestVO.setSupplierOrgId(orgId);
                } else {
                    purchaseRequestVO.setPurchaseOrgId(orgId);
                }
                purchaseRequestVO.setCreateId(getUserId());
                purchaseRequestVO.setCreateOrgId(orgId);

                //分布式锁处理
                String purchaseReuestCacheKey = RedisConstant.purchaseReuestCacheKey(purchaseRequestVO);
                RLock lock = redissonClient.getLock(purchaseReuestCacheKey);
                boolean isLock;
                try {
                    isLock = lock.tryLock(0, 60 * 30, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    log.error("提交采购申请零件获取分布式锁异常：{}", e);
                    return ActionResultUtil.errorActionResult(ErrorCode.Failure);
                }
                if (!isLock) {
                    log.warn("相同采购申请的数据在redis中已存在,无法获取锁，本次不执行");
                    return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(), "操作太快了,请检查是否已经提交");
                }
                try {
                    code = purchaseRequestService.insert(purchaseRequestVO, orgId, "submit", null);
                } catch (Exception e) {
                    lock.unlock();
                    throw new Exception(e);//释放锁，然后把捕捉的到异常原样抛出
                }
            } else {
                code = purchaseRequestService.update(purchaseRequestVO, orgId, "submit");
            }
            return actionResult(code);
        } catch (Exception e) {
            LogHelper.error(JSON.toJSONString(e), ErrorCode.Failure.getCode());
//            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
            throw e;
        }
    }

    @RequestMapping(value = "/auditPass", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult auditPass(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        purchaseRequestVO.setBillStatus(PurchaseStatus.AuditPass.toString());
        purchaseRequestVO.setAuditId(getUserId());
        purchaseRequestVO.setAuditMessage(purchaseRequestVO.getAuditMessage());
        return actionResult(purchaseRequestService.auditBill(purchaseRequestVO, getOrgId(), getUserId()));
    }

    @RequestMapping(value = "/auditRefused", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult auditRefused(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        purchaseRequestVO.setBillStatus(PurchaseStatus.AuditRefused.toString());
        purchaseRequestVO.setAuditId(getUserId());
        purchaseRequestVO.setAuditMessage(purchaseRequestVO.getAuditMessage());
        return actionResult(purchaseRequestService.auditBill(purchaseRequestVO, getOrgId(), getUserId()));
    }

    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult cancel(@RequestBody PurchaseRequestVO purchaseRequestVO) throws Exception {
        try {
            return actionResult(purchaseRequestService.cancel(purchaseRequestVO));
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }


    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult remove(@RequestBody PurchaseRequestVO purchaseRequestVO) {
        purchaseRequestVO.setUpdateId(getUserId());
        return actionResult(purchaseRequestService.remove(purchaseRequestVO));
    }

    @RequestMapping(value = "/item", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String billId, Integer isDirect) throws Exception {
        return actionValueResult(purchaseRequestService.item(billId, isDirect, getOrgId()));
    }

    @RequestMapping(value = "/itemByIds", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult itemByIds(@RequestBody String[] ids) throws Exception {
        return actionValueResult(purchaseRequestService.itemByIds(Arrays.asList(ids), getOrgId()));
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<PurchaseRequestVO> condition) throws Exception {
        PurchaseRequestVO purchaseRequestVO = condition.getFilters();
        String orgId = getOrgId();
        if (purchaseRequestVO.getSeller()) {
            purchaseRequestVO.setSupplierOrgId(orgId);
        } else {
            purchaseRequestVO.setPurchaseOrgId(orgId);
        }
        if (purchaseRequestVO.getOnlySend() != null && purchaseRequestVO.getOnlySend() == 1) {
            purchaseRequestVO.setSoldOrgId(orgId);
        }
        purchaseRequestVO.setCreateOrgId(orgId);
        //处理销售组织筛选
        processSaleCodeList(purchaseRequestVO, orgId, getDeptId());
        condition.setFilters(purchaseRequestVO);
        PageCommonVO pageCommonVO = purchaseRequestService.list(condition, getOrgId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    private void processSaleCodeList(PurchaseRequestVO purchaseRequestVO, String orgId, String deptId) {
        boolean isYn = commonService.checkIsYnOrgId(orgId);
        if (isYn) {
            purchaseRequestVO.setSalesCodeList(commonService.getSalesCodes(deptId));
        }
    }

    /**
     * @Des 采购报表
     * @Date 2020/10/28 17:59
     * @Author wangzhaoyu
     * @Param []
     * @Return void
     */
    @PostMapping("/orderMaterials/report")
    @FastMappingInfo(needLogin = true)
    public ActionResult purchaseRequestReport(@RequestBody SearchCommonVO<PurchaseRequestReportParamVO> condition) throws Exception {
        String orgId = getOrgId();
        PurchaseRequestReportParamVO filters = condition.getFilters();
        if (filters == null) {
            filters = new PurchaseRequestReportParamVO();
        }
        filters.setPurchaseOrgId(orgId);
        filters.setCreateOrgId(orgId);
        condition.setFilters(filters);
        PageCommonVO pageCommonVO = purchaseRequestService.purchaseRequestReport(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    /**
     * @Des 采购报表导出
     * @Date 2020/10/29 10:45
     * @Author wangzhaoyu
     * @Param [requestReportParamVO]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @RequestMapping(value = "/orderMaterials/report/export", method = {RequestMethod.POST, RequestMethod.GET})
    @FastMappingInfo(needLogin = true)
    public ActionResult purchaseRequestReportExport(PurchaseRequestReportParamVO requestReportParamVO) throws Exception {
        String orgId = getOrgId();
        if (requestReportParamVO == null) {
            requestReportParamVO = new PurchaseRequestReportParamVO();
        }
        requestReportParamVO.setPurchaseOrgId(orgId);
        requestReportParamVO.setCreateOrgId(orgId);
        purchaseRequestService.purchaseRequestReportExport(requestReportParamVO);
        return ActionResultUtil.successActionResult();
    }


    @RequestMapping(value = "/download", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void download() throws Exception {
        purchaseRequestService.download();
    }

    @RequestMapping(value = "/downloadReplaceMaterialTemp", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void downloadReplaceMaterialTemp() throws Exception {
        purchaseRequestService.downloadReplaceTemp();
    }

    @ResponseBody
    @RequestMapping(value = "/importFilter", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importFilterExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        String orgId = request.getParameter("x-orgId");
        String dealerOrgId = request.getParameter("x-dealerOrgId");
        String soldOrgId = request.getParameter("x-soldOrgId");
        String isDirectCast = request.getParameter("x-isDirectCast");
        String supplierCode = request.getParameter("x-supplierCode");//供应商代码
        if (StringUtil.isEmpty(orgId)) {
            orgId = getOrgId();
        }
        if (StringUtil.isEmpty(dealerOrgId)) {
            dealerOrgId = getOrgId();
        }

        if (StringUtils.isNotEmpty(isDirectCast) && "0".equals(isDirectCast)) {
            DataDictionaryVO dictVO = dataDictionaryService.itemByCode(SELF_MATERIAL_FILTER, getOrgId());
            if (dictVO != null) {
                orgId = getOrgId();
            }
        }
        if (StringUtil.isNotEmpty(orgId) && !orgId.equals(getOrgId())) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(getOrgId(), orgId);
            if (supplierDO == null || !supplierDO.getIsPlatCompany()) {
                orgId = getOrgId();
            }
        }
        if (!fileName.trim().endsWith(".xls")) {
            return actionResult(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            FunctionResult<String> result = new FunctionResult<>();
            result = purchaseRequestService.importExcel(in, dealerOrgId, orgId, isDirectCast, soldOrgId, supplierCode);
            return actionResult(result.getCode(), result.getValue());
        }
    }


    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        String orgId = request.getParameter("x-orgId");
        String dealerOrgId = request.getParameter("x-dealerOrgId");
        String soldOrgId = request.getParameter("x-soldOrgId");
        String isDirectCast = request.getParameter("x-isDirectCast");
        String supplierCode = request.getParameter("x-supplierCode");//供应商代码
        if (StringUtil.isEmpty(orgId)) {
            orgId = getOrgId();
        }
        if (StringUtil.isEmpty(dealerOrgId)) {
            dealerOrgId = getOrgId();
        }

        if (StringUtil.isNotEmpty(orgId) && !orgId.equals(getOrgId())) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(getOrgId(), orgId);
            if (supplierDO == null || !supplierDO.getIsPlatCompany()) {
                orgId = getOrgId();
            }
        }
        if (!fileName.trim().endsWith(".xls")) {
            return actionResult(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            FunctionResult<String> result = new FunctionResult<>();
            result = purchaseRequestService.importExcel(in, dealerOrgId, orgId, isDirectCast, soldOrgId, supplierCode);
            return actionResult(result.getCode(), result.getValue());
        }
    }

    /**
     * 导入替换零件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/importReplaceMaterial", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importReplaceMaterialExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        String orgId = request.getParameter("x-orgId");
        String dealerOrgId = request.getParameter("x-dealerOrgId");
        String soldOrgId = request.getParameter("x-soldOrgId");
        String isDirectCast = request.getParameter("x-isDirectCast");
        String billId = request.getParameter("x-billId");//采购单号ID
        String supplierCode = request.getParameter("x-supplierCode");//供应商代码

        if (StringUtil.isEmpty(orgId)) {
            orgId = getOrgId();
        }
        if (StringUtil.isEmpty(dealerOrgId)) {
            dealerOrgId = getOrgId();
        }
        if (StringUtil.isNotEmpty(orgId) && !orgId.equals(getOrgId())) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(getOrgId(), orgId);
            if (supplierDO == null || !supplierDO.getIsPlatCompany()) {
                orgId = getOrgId();
            }
        }

        if (StringUtils.isNotEmpty(isDirectCast) && "0".equals(isDirectCast)) {
            DataDictionaryVO dictVO = dataDictionaryService.itemByCode(SELF_MATERIAL_FILTER, getOrgId());
            if (dictVO != null) {
                orgId = getOrgId();
            }
        }

        if (!fileName.trim().endsWith(".xls")) {
            return actionResult(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            FunctionResult<String> result = new FunctionResult<>();
            try {
                result = purchaseRequestService.importReplaceExcel(billId, in, dealerOrgId, orgId, isDirectCast, soldOrgId, supplierCode);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    in.close();
                }
            }
            return actionResult(result.getCode(), result.getValue());
        }
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void export(String[] billIds) throws Exception {
        purchaseRequestService.export(Arrays.asList(billIds));
    }

    @RequestMapping(value = "/exportAll", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportAll(PurchaseRequestVO condition) throws Exception {
        if (condition.getSeller()) {
            condition.setSupplierOrgId(getOrgId());
        } else {
            condition.setPurchaseOrgId(getOrgId());
        }
        condition.setCreateOrgId(getOrgId());
        purchaseRequestService.exportAll(condition);
    }

    @RequestMapping(value = "/exportAllNormal", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportAllNormal(PurchaseRequestVO condition) throws Exception {
        if (condition.getSeller()) {
            condition.setSupplierOrgId(getOrgId());
        } else {
            condition.setPurchaseOrgId(getOrgId());
        }
        condition.setCreateOrgId(getOrgId());
        condition.setIsDirectCast(0);
        purchaseRequestService.exportAll(condition);
    }

    @RequestMapping(value = "/exportAllDirect", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportAllDirect(PurchaseRequestVO condition) throws Exception {
        if (condition.getSeller()) {
            condition.setSupplierOrgId(getOrgId());
        } else {
            condition.setPurchaseOrgId(getOrgId());
        }
        condition.setCreateOrgId(getOrgId());
        condition.setIsDirectCast(1);
        purchaseRequestService.exportAll(condition);
    }

    @RequestMapping(value = "/addressList", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult addressList(@RequestBody SearchCommonVO<PurchaseRequestVO> condition) throws Exception {
        PurchaseRequestVO purchaseRequestVO = condition.getFilters();
        if (purchaseRequestVO.getSeller()) {
            purchaseRequestVO.setSupplierOrgId(getOrgId());
        } else {
            purchaseRequestVO.setPurchaseOrgId(getOrgId());
        }
        purchaseRequestVO.setCreateOrgId(getOrgId());
        condition.setFilters(purchaseRequestVO);
        List<PurchaseRequestDO> prDo = purchaseRequestService.addressList(condition.getFilters());
        return actionValueResult(prDo);
    }

    @RequestMapping(value = "/purchaseGroupList", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult purchaseGroupList(@RequestBody SearchCommonVO<PurchaseGroupDO> condition) throws Exception {
        return actionValueResult(new PageInfo<>(purchaseRequestService.purchaseGroupList(condition)));
    }

//    @RequestMapping(value = "/sapPost", method = RequestMethod.POST)
//    @ApiOperation(value = "调用采购凭证创建接口")
//    @FastMappingInfo(needLogin = true)
//    public ActionResult sapPost(@RequestBody PurchaseRequestVO condition) {
//        ErrorCode errorCode;
//        try {
//            errorCode = purchaseRequestService.sapPost(condition.getBillId(), getOrgId());
//        } catch (Exception e) {
//            LogHelper.monitor(e.getMessage());
//            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
//        }
//        return actionResult(errorCode);
//    }
//
//    @RequestMapping(value = "/sapAdd", method = RequestMethod.POST)
//    @ApiOperation(value = "读取采购订单接口")
//    @FastMappingInfo(needLogin = true)
//    public ActionResult sapAdd(@RequestBody PurchaseRequestVO condition) {
//        try {
//            List<String> list = purchaseRequestService.sapAdd(condition.getSapBillNo(), getUserId(), getOrgId());
//            return actionResult(list);
//        } catch (Exception e) {
//            LogHelper.monitor(e.getMessage());
//            LogHelper.error(getExceptionAllinformation(e), ErrorCode.Failure.getCode());
//            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
//        }
//    }

    @ResponseBody
    @RequestMapping(value = "/importAttach", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importAttach(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String billId = request.getParameter("x-billId");
        return actionResult(purchaseRequestService.importAttach(billId, file));
    }

    @RequestMapping(value = "/downloadAttach", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public void downloadAttach(String billId) throws Exception {
        purchaseRequestService.downloadAttach(billId);
    }

    @RequestMapping(value = "/getDetailByIds", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult getDetailByIds(@RequestBody String[] ids) {
        return actionValueResult(purchaseRequestService.getDetailByIds(Arrays.asList(ids)));
    }

    private String getExceptionAllinformation(Exception ex) {
        String sOut = "\r\n";
        sOut += ex.getMessage();
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    }

    @RequestMapping(value = "/listRequestMaterials", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult listRequestMaterials(@RequestBody SearchCommonVO<PurchaseMaterialsShowVO> condition)
            throws Exception {
        PurchaseMaterialsShowVO showVO = condition.getFilters();
        if (StringUtils.isBlank(showVO.getOrgId())) {
            showVO.setOrgId(getOrgId());
        }
        condition.setFilters(showVO);
        return actionValueResult(purchaseRequestService.listRequestMaterials(condition).getPageInfo());
    }

    @RequestMapping(value = "/exportInventoryReport", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportSaleReport(PurchaseMaterialsShowVO condition) throws Exception {
        condition.setOrgId(getOrgId());
        purchaseRequestService.exportInventoryReport(condition);
    }

    @RequestMapping(value = "/createContract", method = RequestMethod.POST)
    public ActionResult createContract(@RequestBody String[] ids) {
        return actionResult(purchaseRequestService.createContract(ids));
    }

    /**
     * @Desc 采购报表-供货及时性
     * @Author Mr.dong
     * @Date 2021/6/7 9:36
     */
    @RequestMapping(value = "/timelinessReport", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult timelinessReport(@RequestBody SearchCommonVO<TimelinessReportParamVO> condition) throws Exception {

        TimelinessReportParamVO filters = condition.getFilters();
        if (filters == null) {
            filters = new TimelinessReportParamVO();
        }
        if (StringUtils.isEmpty(filters.getOrgId())) {
            filters.setOrgId(getOrgId());
        }

        condition.setFilters(filters);
        PageCommonVO pageCommonVO = purchaseRequestService.timelinessReport(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    /**
     * @Desc 采购报表-供货及时性导出全部
     * @Author Mr.dong
     * @Date 2021/6/7 9:36
     */
    @RequestMapping(value = "/exportTimelinessReportAll", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportTimelinessReportAll(TimelinessReportParamVO condition) throws Exception {
        if (StringUtils.isEmpty(condition.getOrgId())) {
            condition.setOrgId(getOrgId());
        }
        purchaseRequestService.exportTimelinessReport(condition);
    }

    /**
     * @Desc 采购报表-供货及时性导出
     * @Author Mr.dong
     * @Date 2021/6/7 9:36
     */
    @RequestMapping(value = "/exportTimelinessReport", method = RequestMethod.POST)
    public void materialStorageExport(String[] ids) throws Exception {
        if (ids.length <= 0) {
            throw new Exception("选中数据行不能为空");
        }
        TimelinessReportParamVO condition = new TimelinessReportParamVO();
        condition.setBillIds(Arrays.asList(ids));
        purchaseRequestService.exportTimelinessReport(condition);
    }

    /**
     * @Desc 校验参数
     * @Author Mr.dong
     * @Date 2021/2/5 15:05
     */
    private void checkParam(PurchaseRequestVO purchaseRequestVO, String orgId) throws Exception {
        //进出口校验国家、采购合同及零件中机型非空
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
        if (StringUtils.isNotEmpty(companyInfoDO.getSapCode()) && CompanyUtil.JCK_SAP_CODE.equals(companyInfoDO.getSapCode())) {
            //校验国家
            if (StringUtils.isEmpty(purchaseRequestVO.getCountry())) {
                throw new Exception("国家不能为空！");
            }
            if (StringUtils.isEmpty(purchaseRequestVO.getPurchaseContractNo())) {
                throw new Exception("采购合同号不能为空！");
            }
            List<PurchaseRequestDetailVO> materialsList = purchaseRequestVO.getMaterialsList();
            for (PurchaseRequestDetailVO materials : materialsList) {
                if (StringUtils.isEmpty(materials.getMachineModel())) {
                    throw new Exception("零件【" + materials.getMaterialsNo() + "】适用机型不能为空！");
                }
            }

        }

    }

//    @RequestMapping(value = "/syncOrder", method = RequestMethod.GET)
//    public ActionResult syncOrder(String billId) throws Exception {
//        purchaseRequestService.syncOrder(billId);
//        return actionResult(ErrorCode.Success);
//    }
//
//    @RequestMapping(value = "/pullStockInfo", method = RequestMethod.GET)
//    public ActionResult pullStockInfo() throws Exception {
//        purchaseRequestService.setPullRecord();
//        purchaseRequestService.pullStockInfo();
//        return actionResult(ErrorCode.Success);
//    }

}



